package com.hongye.why.base.listenin;

/**
 * 发送链表
 */
final class MessagePosterQueue {
    /**
     * 链表头部
     */
    private MessagePoster head;
    /**
     * 链表尾部
     */
    private MessagePoster tail;

    MessagePosterQueue() {

    }

    /**
     * 在链表尾部接入poster
     * @param poster MessagePoster
     */
    synchronized void enqueue(MessagePoster poster) {
        if (null == poster) {
            throw new NullPointerException("null MessagePoster cannot be enqueued");
        } else {
            if (this.tail != null) {
                this.tail.next = poster;
                this.tail = poster;
            } else {
                if (this.head != null) {
                    throw new IllegalStateException("Present a head, but no tail");
                }
                this.head = this.tail = poster;
            }
            this.notifyAll();
        }
    }

    synchronized MessagePoster poll() {
        MessagePoster messagePoster = this.head;
        if (this.head != null) {
            this.head = this.head.next;
            if (this.head == null) {
                this.tail = null;
            }
            messagePoster.next = null;
        }
        return messagePoster;
    }

    synchronized MessagePoster poll(int maxMillisToWait) throws InterruptedException {
        if (null == this.head) {
            this.wait(maxMillisToWait);
        }
        return this.poll();
    }
}
